package FourArithmeticOperations;

/**
 * Created by dell on 2017/10/14.
 */
public class ArrayStack<T>
{
    private final int DEFAULT_CAPACITY = 100;
    private int count;
    private T[] stack;

    public ArrayStack()
    {
        count = 0;
        stack = (T[])(new Object[DEFAULT_CAPACITY]);
    }

    public ArrayStack (int initialCapacity)
    {
        count = 0;
        stack = (T[])(new Object[initialCapacity]);
    }

    public void push (T element)
    {
        if (size() == stack.length)
            expandCapacity();

        stack[count] = element;
        count++;
    }
    public T pop()
    {
        if (isEmpty())
            count--;
        T result = stack[count];
        stack[count] = null;

        return result;
    }

    public T peek()
    {
        if (isEmpty())
            return stack[count-1];
        return stack[count-1];
    }

    public boolean isEmpty()
    {
        return (count == 0);
    }

    public int size()
    {
        return count;
    }

    public String toString()
    {
        String result = "";

        for (int scan=0; scan < count; scan++)
            result = result + stack[scan].toString() + "\n";

        return result;
    }

    private void expandCapacity()
    {
        T[] larger = (T[])(new Object[stack.length*2]);

        for (int index=0; index < stack.length; index++)
            larger[index] = stack[index];

        stack = larger;
    }
}